﻿using System;
using System.Threading;
using GameTools;
using ServiceStack.WebHost.Endpoints;

namespace DTFight
{
	class MainClass
	{
		static void  CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
		{
			Log.WriteLog(string.Format("应用程序出现异常，请重新启动！异常情况如下:\r\n{0}", e.ExceptionObject.ToString()));


			Environment.Exit(0); //0代表正常退出，非0代表某种错误的退出
		}

		public static void Main (string[] args)
		{
			// 防止自动弹出“XXXX程序已停止工作”的对话框
			AppDomain.CurrentDomain.UnhandledException +=new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

			string url = "http://120.27.34.224:1338/";
			string lanUrl = "http://192.168.1.4:1338/";
			string localUrl = "http://127.0.0.1:1338/";
			var appHost = new DTFightServiceHost ();
			appHost.Init ();
            appHost.Start(localUrl);

			Console.WriteLine("AppHost Created at {0}, listening on {1}", DateTime.Now, url);

			init();
			update();

			Console.ReadKey ();

			destroy();
		}

		static void init()
		{
			//ClientMgr.Instance ().Init ();
			RoomMsg.Instance ().Init ();
			GameMgr.Instance.Init ();

			//NetworkDispatcher.Instance.CreateServer ("127.0.0.1", 50010);
			//NetworkDispatcher.Instance.CreateServer ("120.27.34.224", 50000);
		}

		static void destroy()
		{
			GameMgr.Instance.Destroy ();
			RoomMsg.Instance ().Destroy ();
			//ClientMgr.Instance ().Init ();
		}

		static void update()
		{
			AutoResetEvent myEvent = new AutoResetEvent(false);
			while (true) {
				DateTime preTime = DateTime.Now;

				//NetworkDispatcher.Instance.Update ();
				GameMgr.Instance.Update ();

				TimeSpan time = DateTime.Now - preTime;
				if (time.TotalMilliseconds < 20)
				{
					myEvent.WaitOne((int)(20 - time.TotalMilliseconds)); 
				}
			}
		}

		public class DTFightServiceHost : AppHostHttpListenerBase
		{
			/// <summary>
			/// Default constructor.
			/// Base constructor requires a name and assembly to locate web service classes. 
			/// </summary>
			public DTFightServiceHost()
				: base("DTFight Web Services", typeof(DTFightService).Assembly)
			{

			}

			/// <summary>
			/// Application specific configuration
			/// This method should initialize any IoC resources utilized by your web service classes.
			/// </summary>
			/// <param name="container"></param>
			public override void Configure(Funq.Container container)
			{
				//Config examples
				//this.AddPlugin(new PostmanFeature());
				//this.AddPlugin(new CorsFeature());
			}
		}
	}
}
